import { ComponentClass } from 'react'
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { default as ProductUtils } from '../../utils/product'
import { User as UserUtils } from '../../utils/user'
import { Utils } from '../../utils/utils'
import CollectionService from '../../services/collect'
import Constants from '../../config/constants'

import './index.scss'

const productUtils = new ProductUtils()
const userUtils = new UserUtils()
const utils = new Utils()
const collectionService = new CollectionService()

type PageStateProps = {
  userApplyList: any[],   // 用户申请列表
  userCollectionList: any[],    // 收藏列表
  isLoginValid: boolean,    // 登录是否有效
}

type PageDispatchProps = {
  dispatchRefreshCollect: () => void,
}

type PageOwnProps = {
  product: any,   // 产品对象
  currentUrl: string,     // 当前页面的url
  eventRandomSuffix: string,    // 事件的随机数
}

type PageState = {
  isCollected: boolean,   // 是否已收藏
  applyCount: number,     // 产品申请次数, 默认是0
  collectId: string,      // 该产品的收藏id, 当前用户有收藏过则有
  isCollecLoading: boolean,   // 是否正在发送收藏请求
}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface ProductFormButtonGroup {
  props: IProps;
  state: PageState;
}

/**
 * 产品详情按钮组件
 */
@connect(({ common }) => ({
  ...common
}), (dispatch) => ({
  dispatchRefreshCollect() {
    dispatch({
      type: 'common/refreshUserCollectionList',
      payload: {},
    })
  }
}))
class ProductFormButtonGroup extends Component {

  constructor(props) {
    super(props);

    this.state = {
      isCollected: false,
      applyCount: 0,
      collectId: '',
      isCollecLoading: false,
    }
  }

  componentWillReceiveProps(nextProps) {
    
    const { product, userCollectionList, userApplyList } = nextProps

    if (product) {      
      // 重新计算收藏状态
      this.setCollectState(userCollectionList, product)
      // 计算申请次数
      this._initProcuctApplyParam(userApplyList, product)
    }
  }

  componentDidMount() {
    // const { userCollectionList, product } = this.props

    // 计算收藏状态
    // this.setCollectState(userCollectionList, product)
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  render() {
    // const { product, userApplyList } = this.props
    const { isCollected, applyCount } = this.state

    return (<View className="function-button-group-container">
      <Button className="image-button first-button-bgc" onClick={this.onCollect}>
        <Text className={`iconfont icon-shoucang top-icon ${isCollected ? 'yellow' : ''}`} />
        <Text className={`small-text ${isCollected ? 'yellow' : ''}`}> {isCollected ? '已收藏' : '收藏'}</Text>
      </Button>
      <Button openType="share" className="image-button second-button-bgc">
        <Text className="iconfont icon-fenxiang top-icon white" />
        <Text className="small-text white">分享</Text>
      </Button>
      <Button className="image-button third-button-bgc" onClick={this.onApply}>
        <Text className="apply-text white">
          {
            applyCount === 0 ? '立即申请' : `再次申请(已申请过${applyCount}次)`
          }
        </Text>
      </Button>
    </View >
    )
  }

  /**
   * 收藏产品的处理方法
   * @param e 
   */
  onCollect = (e) => {
    // console.log('onCollect, e = ', e)

    const url = this.props.currentUrl
    const isLoginValid = userUtils.isLoginValid()

    // 请求中，则不重复请求
    if (this.state.isCollecLoading) {
      return 
    }

    if (isLoginValid) {
      const { isCollected, collectId } = this.state

      // 收藏产品
      if (isCollected && collectId) {
        
        // 已收藏就取消收藏
        // utils.showLoadingCenter()

        this.setState({
          isCollecLoading: true
        })

        collectionService.removeCollection([collectId])
          .then(res => {
            // console.log('取消收藏成功, res = ', res)
            this.setState({
              isCollected: false,
              collectId: '',
              isCollecLoading: false,
            })
            
            // utils.hideLoadingCenter()
            
            setTimeout(() => {
              Taro.showToast({
                title: '取消成功',
                icon: 'success',
              })
            }, 10)
            
          }, error => {
            // utils.hideLoadingCenter()
            console.error('取消收藏有异常:', error)
          }).then(res => {
            // 重新查询已收藏产品列表，获取当前收藏产品的收藏id
            this.props.dispatchRefreshCollect()
          })
      } else {
        // 未收藏则收藏
        // utils.showLoadingCenter()

        this.setState({
          isCollecLoading: true
        })

        collectionService.addCollection(this.props.product)
          .then(res => {
           
            // console.log('收藏成功, res = ', res)
            // utils.hideLoadingCenter()
            
            setTimeout(() => {
              Taro.showToast({
                title: '收藏成功',
                icon: 'success',
              })
            }, 10)

            this.setState({
              isCollected: true,
              isCollecLoading: false,
            })
          }, error => {
            this.setState({
              isCollecLoading: false,
            })
            // utils.hideLoadingCenter()
            console.error('收藏有异常:', error)
          })
          .then(res => {
            // 重新查询已收藏产品列表，获取当前收藏产品的收藏id
            this.props.dispatchRefreshCollect()
          })
      }
    } else {
      userUtils.checkIsLogin(url)
    }
  }

  /**
   * 更新收藏状态
   * @param collecitonList 
   * @param product 
   */
  setCollectState(collecitonList: any[], product: any) {
    const collectId = productUtils.getCollectionId(collecitonList, product)
    this.setState({
      collectId,
      isCollected: collectId ? true : false
    })
  }

  /**
   * 申请产品的处理方法
   * @param {*} e 
   */
  onApply = (e) => {
    // 发送申请事件
    Taro.eventCenter.trigger(`${Constants.FORM_GROUP_APPLY_EVENT}${this.props.eventRandomSuffix}`, {})
  }

  /**
   * 初始化产品申请参数
   * @param applyList 产品申请列表
   * @param product 产品
   */
  _initProcuctApplyParam(applyList: any[], product: any) {
    const applyCount = productUtils.getProductApplyCount(applyList, product)

    this.setState({
      applyCount,
    })
  }
}

export default ProductFormButtonGroup as ComponentClass<PageOwnProps, PageState>
